/* clipboard.c */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "clipboard.h"

clip_t * clip_new(){
	clip_t * cl = NULL;
	if((cl = (clip_t *)malloc(sizeof(clip_t))) == NULL){
		fputs("Out of memory while allocating tabmap!",stderr);
		exit(1);
	}
	cl->clip_type = CLIP_STRING;
	cl->string = NULL;
	cl->buf_stack.buf_num = 0;
	cl->buf_stack.stack = NULL;
	return cl;
}

int clip_free(clip_t * clip){
	if(clip->clip_type == CLIP_STRING){
		free(clip->string);
	}else{
		int i;
		
		if(clip->buf_stack.stack!= NULL){
			for(i=0; i<clip->buf_stack.buf_num; i++){
				if(clip->buf_stack.stack[i]!= NULL)
					buf_free(clip->buf_stack.stack[i]);
			}
			free(clip->buf_stack.stack);
		}
	}
	free(clip);
	return 0;
}

int clipboard_add_clip(clipboard_t *cb, clip_t * clip){
	if(cb->clip == clip){
		return 0;
	}else if(cb->clip != NULL){
		clip_free(cb->clip);
	}
	cb->clip = clip;
	return 0;
}

int clipboard_clear(clipboard_t * cb){
	if(cb->clip != NULL){
		clip_free(cb->clip);
	}
	cb->clip = NULL;
	return 0;
}

int allocate_buf_array(bufstack_t * bs, int buf_num){
	buf_t ** buf_ptr = NULL;	
	if((buf_ptr = (buf_t **)malloc(sizeof(buf_t *)*buf_num)) == NULL){
		fputs("Out of memory while allocating buffer array!",stderr);
		exit(1);
	}
	bs->stack = buf_ptr;
	bs->buf_num = buf_num;
	return 0;
}
